using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CKY.AgentPlatform.ModelConfigs
{
    /// <summary>
    /// 模型API调用模式枚举
    /// </summary>
    public enum ModelApiMode
    {
        /// <summary>
        /// 自有API模式 - 使用模型原生的API接口
        /// </summary>
        Native = 0,

        /// <summary>
        /// OpenAI兼容模式 - 使用OpenAI格式的API接口
        /// </summary>
        OpenAICompatible = 1,

        /// <summary>
        /// 自动模式 - 优先尝试OpenAI兼容模式，失败后回退到自有API模式
        /// </summary>
        Auto = 2,

        /// <summary>
        /// 自定义模式 - 使用完全自定义的调用逻辑
        /// </summary>
        Custom = 3
    }

    /// <summary>
    /// 模型提供商能力特征
    /// </summary>
    [Flags]
    public enum ModelProviderCapabilities
    {
        /// <summary>
        /// 无特殊能力
        /// </summary>
        None = 0,

        /// <summary>
        /// 支持流式输出
        /// </summary>
        Streaming = 1 << 0,

        /// <summary>
        /// 支持函数调用
        /// </summary>
        FunctionCalling = 1 << 1,

        /// <summary>
        /// 支持多模态输入
        /// </summary>
        Multimodal = 1 << 2,

        /// <summary>
        /// 支持JSON模式
        /// </summary>
        JsonMode = 1 << 3,

        /// <summary>
        /// 支持系统提示词
        /// </summary>
        SystemPrompt = 1 << 4,

        /// <summary>
        /// 支持工具调用
        /// </summary>
        ToolCalling = 1 << 5,

        /// <summary>
        /// 支持Vision图像识别
        /// </summary>
        Vision = 1 << 6,

        /// <summary>
        /// 支持异步处理
        /// </summary>
        AsyncProcessing = 1 << 7
    }

    /// <summary>
    /// 模型调用配置
    /// </summary>
    public class ModelInvocationConfig
    {
        /// <summary>
        /// API调用模式
        /// </summary>
        public ModelApiMode ApiMode { get; set; } = ModelApiMode.Auto;

        /// <summary>
        /// 自有API端点URL
        /// </summary>
        public string NativeApiEndpoint { get; set; }

        /// <summary>
        /// OpenAI兼容API端点URL
        /// </summary>
        public string OpenAICompatibleEndpoint { get; set; }

        /// <summary>
        /// 优先使用的API模式（当ApiMode=Auto时）
        /// </summary>
        public ModelApiMode PreferredMode { get; set; } = ModelApiMode.OpenAICompatible;

        /// <summary>
        /// 是否启用回退机制
        /// </summary>
        public bool EnableFallback { get; set; } = true;

        /// <summary>
        /// 回退超时时间（毫秒）
        /// </summary>
        public int FallbackTimeoutMs { get; set; } = 10000;

        /// <summary>
        /// 最大重试次数
        /// </summary>
        public int MaxRetries { get; set; } = 3;

        /// <summary>
        /// 自定义请求头
        /// </summary>
        public Dictionary<string, string> CustomHeaders { get; set; } = new Dictionary<string, string>();

        /// <summary>
        /// 自定义查询参数
        /// </summary>
        public Dictionary<string, string> CustomQueryParams { get; set; } = new Dictionary<string, string>();

        /// <summary>
        /// 模型特定参数
        /// </summary>
        public Dictionary<string, object> ModelSpecificParams { get; set; } = new Dictionary<string, object>();

        /// <summary>
        /// 能力配置
        /// </summary>
        public ModelProviderCapabilities Capabilities { get; set; } = ModelProviderCapabilities.None;

        /// <summary>
        /// 支持的模型列表
        /// </summary>
        public List<string> SupportedModels { get; set; } = new List<string>();

        /// <summary>
        /// 验证配置是否有效
        /// </summary>
        /// <returns>是否有效</returns>
        public bool IsValid()
        {
            switch (ApiMode)
            {
                case ModelApiMode.Native:
                    return !string.IsNullOrWhiteSpace(NativeApiEndpoint);
                case ModelApiMode.OpenAICompatible:
                    return !string.IsNullOrWhiteSpace(OpenAICompatibleEndpoint);
                case ModelApiMode.Auto:
                    return !string.IsNullOrWhiteSpace(NativeApiEndpoint) ||
                           !string.IsNullOrWhiteSpace(OpenAICompatibleEndpoint);
                case ModelApiMode.Custom:
                    return true; // 自定义模式由具体实现验证
                default:
                    return false;
            }
        }

        /// <summary>
        /// 获取指定模式的端点URL
        /// </summary>
        /// <param name="mode">API模式</param>
        /// <returns>端点URL</returns>
        public string GetEndpointForMode(ModelApiMode mode)
        {
            return mode switch
            {
                ModelApiMode.Native => NativeApiEndpoint,
                ModelApiMode.OpenAICompatible => OpenAICompatibleEndpoint,
                _ => throw new ArgumentException($"不支持的API模式: {mode}")
            };
        }

        /// <summary>
        /// 检查是否支持特定能力
        /// </summary>
        /// <param name="capability">能力</param>
        /// <returns>是否支持</returns>
        public bool HasCapability(ModelProviderCapabilities capability)
        {
            return Capabilities.HasFlag(capability);
        }

        /// <summary>
        /// 检查是否支持模型
        /// </summary>
        /// <param name="modelName">模型名称</param>
        /// <returns>是否支持</returns>
        public bool SupportsModel(string modelName)
        {
            return SupportedModels == null || SupportedModels.Count == 0 ||
                   SupportedModels.Contains(modelName, StringComparer.OrdinalIgnoreCase);
        }
    }

    /// <summary>
    /// 模型提供商注册信息
    /// </summary>
    public class ModelProviderRegistration
    {
        /// <summary>
        /// 提供商名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 提供商类型
        /// </summary>
        public ModelProvider ProviderType { get; set; }

        /// <summary>
        /// 默认API模式
        /// </summary>
        public ModelApiMode DefaultApiMode { get; set; }

        /// <summary>
        /// 默认配置
        /// </summary>
        public ModelInvocationConfig DefaultConfig { get; set; }

        /// <summary>
        /// 适配器类型
        /// </summary>
        public Type AdapterType { get; set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;

        /// <summary>
        /// 优先级（数字越小优先级越高）
        /// </summary>
        public int Priority { get; set; } = 100;

        /// <summary>
        /// 版本信息
        /// </summary>
        public string Version { get; set; }

        /// <summary>
        /// 描述信息
        /// </summary>
        public string Description { get; set; }
    }

    /// <summary>
    /// 模型调用请求
    /// </summary>
    public class ModelInvocationRequest
    {
        /// <summary>
        /// 模型名称
        /// </summary>
        public string Model { get; set; }

        /// <summary>
        /// 消息列表
        /// </summary>
        public List<ChatMessage> Messages { get; set; }

        /// <summary>
        /// 最大令牌数
        /// </summary>
        public int MaxTokens { get; set; } = 4000;

        /// <summary>
        /// 温度值
        /// </summary>
        public double Temperature { get; set; } = 0.7;

        /// <summary>
        /// Top P值
        /// </summary>
        public double TopP { get; set; } = 1.0;

        /// <summary>
        /// 流式输出
        /// </summary>
        public bool Stream { get; set; } = false;

        /// <summary>
        /// 停止序列
        /// </summary>
        public List<string> Stop { get; set; }

        /// <summary>
        /// 频率惩罚
        /// </summary>
        public double FrequencyPenalty { get; set; } = 0;

        /// <summary>
        /// 存在惩罚
        /// </summary>
        public double PresencePenalty { get; set; } = 0;

        /// <summary>
        /// 工具调用配置
        /// </summary>
        public List<ToolCallConfig> Tools { get; set; }

        /// <summary>
        /// 响应格式
        /// </summary>
        public ResponseFormat ResponseFormat { get; set; }

        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserId { get; set; }

        /// <summary>
        /// 会话ID
        /// </summary>
        public string SessionId { get; set; }

        /// <summary>
        /// 自定义元数据
        /// </summary>
        public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();
    }

    /// <summary>
    /// 工具调用配置
    /// </summary>
    public class ToolCallConfig
    {
        /// <summary>
        /// 工具类型
        /// </summary>
        public string Type { get; set; } = "function";

        /// <summary>
        /// 函数定义
        /// </summary>
        public FunctionDefinition Function { get; set; }
    }

    /// <summary>
    /// 函数定义
    /// </summary>
    public class FunctionDefinition
    {
        /// <summary>
        /// 函数名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 函数描述
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// 参数定义
        /// </summary>
        public object Parameters { get; set; }
    }

    /// <summary>
    /// 响应格式
    /// </summary>
    public class ResponseFormat
    {
        /// <summary>
        /// 格式类型
        /// </summary>
        public string Type { get; set; } = "text";

        /// <summary>
        /// JSON Schema
        /// </summary>
        public object JsonSchema { get; set; }
    }

    /// <summary>
    /// 模型调用响应
    /// </summary>
    public class ModelInvocationResponse
    {
        /// <summary>
        /// 响应ID
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 对象类型
        /// </summary>
        public string Object { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime Created { get; set; }

        /// <summary>
        /// 模型名称
        /// </summary>
        public string Model { get; set; }

        /// <summary>
        /// 响应消息
        /// </summary>
        public ResponseMessage Response { get; set; }

        /// <summary>
        /// 使用统计
        /// </summary>
        public UsageInfo Usage { get; set; }

        /// <summary>
        /// 工具调用
        /// </summary>
        public List<ToolCall> ToolCalls { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public ErrorResponse Error { get; set; }

        /// <summary>
        /// 使用的API模式
        /// </summary>
        public ModelApiMode UsedApiMode { get; set; }

        /// <summary>
        /// 响应时间（毫秒）
        /// </summary>
        public long ResponseTimeMs { get; set; }

        /// <summary>
        /// 元数据字典
        /// </summary>
        public Dictionary<string, object> Metadata { get; set; }

        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success => Error == null;
    }

    /// <summary>
    /// 响应消息
    /// </summary>
    public class ResponseMessage
    {
        /// <summary>
        /// 角色名称
        /// </summary>
        public string Role { get; set; }

        /// <summary>
        /// 消息内容
        /// </summary>
        public string Content { get; set; }

        /// <summary>
        /// 工具调用
        /// </summary>
        public List<ToolCall> ToolCalls { get; set; }
    }

    /// <summary>
    /// 使用统计
    /// </summary>
    public class UsageInfo
    {
        /// <summary>
        /// 提示词令牌数
        /// </summary>
        public int PromptTokens { get; set; }

        /// <summary>
        /// 完成令牌数
        /// </summary>
        public int CompletionTokens { get; set; }

        /// <summary>
        /// 总令牌数
        /// </summary>
        public int TotalTokens { get; set; }
    }

    /// <summary>
    /// 错误响应
    /// </summary>
    public class ErrorResponse
    {
        /// <summary>
        /// 错误代码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 错误类型
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// 参数信息
        /// </summary>
        public Dictionary<string, object> Param { get; set; }

        /// <summary>
        /// 内部异常信息
        /// </summary>
        public Exception InnerException { get; set; }
    }
}